<?php
/**
 * Класс проверки соответствия данной сессии браузеру пользователя.
 */
class Workset_Session_Validator_Browser extends Zend_Session_Validator_Abstract
{
	const SOLD = 'afsf2893GHJG87gkjhsda98yGJKHG87hk';
	const USER_AGENT = 'User-Agent';
	const AUTHORIZATION = 'Authorization';

	/**
	 * @return void
	 */
	public function setup()
	{
		$aValidData = array();
		$sSold = self::SOLD.__CLASS__;

		if ($sValue = Zend_Controller_Front::getInstance()->getRequest()->getHeader(self::USER_AGENT))
		{
			$aValidData[self::USER_AGENT] = md5($sSold.$sValue);
		}

		if ($sValue = Zend_Controller_Front::getInstance()->getRequest()->getHeader(self::AUTHORIZATION))
		{
			$sUri = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();

			if (isset($aValidData[self::AUTHORIZATION.'_Uri']) && $aValidData[self::AUTHORIZATION.'_Uri'] != $sUri)
			{
				$aValidData[self::AUTHORIZATION] = md5($sSold.reset(explode(',',$sValue)));
			}
			else
			{
				$aValidData[self::AUTHORIZATION.'_Uri'] = $sUri;
			}
		}
		elseif (isset($aValidData[self::AUTHORIZATION.'_Uri']))
		{
			unset($aValidData[self::AUTHORIZATION.'_Uri']);
		}

		$this->setValidData($aValidData);
	}

	/**
	 * @return bool
	 */
	public function validate()
	{
		$bResult = true;
		$aValidData = $this->getValidData();
		$sSold = self::SOLD.__CLASS__;

		if ($bResult && isset($aValidData[self::USER_AGENT]))
		{
			$sValue = Zend_Controller_Front::getInstance()->getRequest()->getHeader(self::USER_AGENT);
			$bResult = $aValidData[self::USER_AGENT] == md5($sSold.$sValue);
		}

		if ($bResult && isset($aValidData[self::AUTHORIZATION]))
		{
			$sValue = Zend_Controller_Front::getInstance()->getRequest()->getHeader(self::AUTHORIZATION);
			$bResult = $aValidData[self::AUTHORIZATION] == md5($sSold.reset(explode(',',$sValue)));
		}

		return $bResult;
	}
}